package com.uh.microservice.core.actor;

import akka.actor.UntypedActor;
import akka.event.LoggingAdapter;
import akka.event.Logging;
import com.uh.microservice.core.dao.JdbcDao;
import com.uh.microservice.core.dto.AkkaMsg;
import com.uh.microservice.core.service.ProxyService;
import com.uh.microservice.core.service.ScriptComponent;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * actor消息处理主体
 * @author liming
 * @date 2017/9/15
 */
@Component("workerActor")
@Scope("prototype")
public class WorkerActor extends UntypedActor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //private LoggingAdapter logger = Logging.getLogger(getContext().system(), this);

    private final CompletableFuture<Object> future;
    private int count = 0;
    public WorkerActor(CompletableFuture<Object> f) {
        this.future = f;
   }

    @Autowired
    private ProxyService proxy;

    @Autowired
    private ScriptComponent scriptComponent;

    @Autowired
    private JdbcDao dao;

    /**
     *  从AKKA中收到消息的回调
     */
    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof AkkaMsg){
            AkkaMsg akkamsg=(AkkaMsg)message;
            logger.debug("AKKA收到数据:",akkamsg.toString());
            Long waitTime=akkamsg.getWaitTime();
            if(waitTime>0){
                Thread.currentThread().sleep(waitTime*1000);
            }
            Object obj=process(akkamsg);
            future.complete(obj);
            logger.debug("AKKA处理完毕:"+akkamsg.getId());

            getContext().stop(getSelf());
            logger.debug("AKKA actor已经停止:"+akkamsg.getId());
        }else{
            unhandled(message);
        }
    }

    /**
     *  收到消息后具体的处理方法
     */
    private Object process(AkkaMsg msg){
        String fn=msg.getFn();
        Object body=msg.getBody();
        Integer id=msg.getId();

        if(StringUtils.startsWithIgnoreCase(fn,"script:")){
            fn=fn.replaceAll("script:","");
            Map params=new HashMap();
            params.put("db",dao);
            params.put("prm",body);
            return scriptComponent.excute(fn,params);
        }else
            return proxy.invoke(fn,body,id);
    }
}
